package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApUnlikesBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApUnLikesBehaviorService;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.behavior.dtos.UnLikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUnLikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements ApUnLikesBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 不喜欢行为记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        //1、检查参数
        if (dto==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数不能为空");
        }
        //2.查询行为实体（方法：findByUserIdOrEquipmentId）
        //获取用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        //判断查询用户行为实体对象是否为空
        if(apBehaviorEntry == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数不能为空");
        }
        //3、不喜欢行为  根据文章id和行为id来获取不喜欢行为对象
        ApUnlikesBehavior apUnlikesBehavior=getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId,dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId,apBehaviorEntry.getId()));
        //判断不喜欢对象是否存在
        if (apUnlikesBehavior==null){
            ApUnlikesBehavior unlikesBehavior = new ApUnlikesBehavior();
            unlikesBehavior.setEntryId(apBehaviorEntry.getId());
            unlikesBehavior.setArticleId(dto.getArticleId());
            unlikesBehavior.setType(dto.getType());
            unlikesBehavior.setCreatedTime(new Date());
            save(unlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            apUnlikesBehavior.setType(dto.getType());
            apUnlikesBehavior.setCreatedTime(new Date());
            updateById(apUnlikesBehavior);//修改点赞行为对象
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
